import { Authenticator } from "remix-auth";
import { FormStrategy } from "remix-auth-form";
import { getUserByUsernameAndPassword, UserModel } from "./models/users";
import { z } from "zod";
import i18nServer from "~/i18n/i18n.server";

export interface AuthenticatorResponse {
  code: number;
  user?: UserModel;
  error?: Record<string, string[]>;
}
export const authenticator = new Authenticator();

authenticator.use(
  new FormStrategy(async ({ form, request }) => {
    const t = await i18nServer.getFixedT(request);
    const account = z.object({
      username: z.string().min(1, { message: t("username") + t("space") + t("required") }),
      password: z.string().min(1, { message: t("password") + t("space") + t("required") }),
    });

    const data = Object.fromEntries(form);
    const result = account.safeParse(data);
    if (!result.success) {
      const error = result.error.flatten();
      return {
        code: 1,
        error: error.fieldErrors,
      };
    }

    const user = await getUserByUsernameAndPassword(result.data.username, result.data.password);
    if (!user) {
      return {
        code: 1,
        error: {
          username: t("username_or_password_error"),
        }
      }
    } else {
      return {
        code: 0,
        user,
      }
    }
  }),
  "user-pass"
);